<template>
  <div class="cluster recovery">
    <a-card style="width: 100%; height:auto">
      <p slot="title" class="cardTitles">
        <span>试卷创编</span>
        <a-button v-if="type!==0" type="primary" style="float: right" @click="backClick">返回</a-button>
      </p>
      <div class="paper-content">
        <a-form-model
          ref="form"
          :model="form"
          :rules="rules"
          v-bind="formLayout"
        >
          <a-form-model-item label="试卷类型" prop="type">
            <a-select v-model="form.type" style="width: 180px" :disabled="type===2">
              <a-select-option v-for="type in typeData" :key="type">
                {{ type }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="站段" prop="section">
            <a-select v-model="form.section" style="width: 180px" :disabled="type===2">
              <a-select-option v-for="section in sectionData" :key="section">
                {{ section }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="试卷名称" prop="name">
            <a-input v-model="form.name" autocomplete="off" :disabled="type===2" />
          </a-form-model-item>
          <a-form-model-item label="题目设置" prop="questionList">
            <div>
              <a-button type="primary" @click="addClick" :disabled="type===2">添加题目</a-button>
            </div>
            <a-card class="card" v-if="form.questionList.length !== 0" style="max-height:500px;overflow:auto">
              <ul>
                <li v-for="(item, index) in form.questionList" :key="item.id">
                  <span class="questionIndex">题目{{ index + 1 }}:</span>
                  <div class="questionContent">{{ item.question }}</div>
                  <span class="delectBtn" @click="deleteItem(index)" v-if="type!==2">删除</span>
                </li>
              </ul>
            </a-card>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }" v-if="type!==2">
            <a-button type="primary" @click="onSubmit">提交 </a-button>
            <a-button style="margin-left: 10px" @click="resetForm">
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-card>
    <add-question
      :questionVisible="questionVisible"
      @selectQuestion="selectQuestion"
      @closeFunc="questionVisible = false"
    />
  </div>
</template>

<script>
import addQuestion from "components/configuration/testPaper/addQuestion";
import { addTemplate,updateTemplate,getTemplateDetail} from "@/api/templates";
import { getSectionArr } from "@/assets/js/utils";
import question from "@/assets/json/questionList.js";
export default {
  components: {
    addQuestion,
  },
  data() {
    return {
      //弹框
      questionVisible: false,
      sectionData: getSectionArr(),
      typeData: ["非正常行车"],
      //选中的id
      selectId: [],
      form: {
        name: "",
        section: "",
        type: "",
        questionList: [],
      },
      formLayout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
      },
      rules: {
        name: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
        section: [{ required: true, message: "请选择站段", trigger: "change" }],
        type: [{ required: true, message: "请选择类型", trigger: "change" }],
        questionList: [{ required: true, message: "添加试卷题目" }],
      },
      type:0,//0是新增1是编辑//2是预览
      id:''
    };
  },
  mounted () {
    this.type = this.$route.query.type==undefined?0:this.$route.query.type;
    this.id=this.$route.query.id
    if(this.type !==0){
      this.getTemplate()
    } else {
      if(localStorage.getItem("selectKey")){
          localStorage.removeItem("selectKey")
      }
    }
  },
  methods: {
    backClick() {
      this.$router.go(-1);
    },
    //获取试卷详情
    getTemplate(){
      getTemplateDetail(this.id)
        .then((res) => {
          this.form.section = res.data.section;
          this.form.name = res.data.name;
          this.form.type = res.data.type;
          var questionList = question()
          this.selectId = res.data.questions
          questionList.forEach((item,index) => {
            for(var i=0;i<res.data.questions.length;i++){
              if(res.data.questions[i] == item.id){
                this.form.questionList.push(item)
              }
            }
          });
          localStorage.setItem("selectKey", JSON.stringify(res.data.questions));
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    //增加题目弹框
    addClick() {
      this.questionVisible = true;
    },
    selectQuestion(val) {
      this.form.questionList = val.selectedRows;
      this.selectId = val.selectedRowKeys;
    },
    deleteItem(index) {
      this.form.questionList.splice(index, 1);
      this.selectId.splice(index, 1);
      localStorage.setItem("selectKey", JSON.stringify(this.selectId));
    },
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var params = {
            name:this.form.name,
            section:this.form.section,
            type:this.form.type,
            questions:this.selectId
          };
          if (this.type == 1) {
            params.id = this.id;
            this.updateSubmit(params);
          } else {
            this.addSubmit(params);
          }
        } else {
          return false;
        }
      });
    },
    addSubmit(params) {
      addTemplate(params)
        .then((res) => {
          if(res.code ===2){
            this.$message.error(res.msg)
            return false
          }
          if (res.data.ok) {
            this.$message.success("添加成功");
            localStorage.removeItem("selectKey")
            this.$router.push('/console/configuration/testPaper/index')
          } else {
            console.log(res.data.errDatas[0].err);
            this.$message.error(res.data.errDatas[0].err);
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {
        });
    },
    updateSubmit(params) {
      updateTemplate(params)
        .then((res) => {
          this.$message.destroy();
          this.$message.success("编辑成功");
          localStorage.removeItem("selectKey")
          this.$router.push('/console/configuration/testPaper/index')
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {

        });
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
  },
};
</script>

<style lang="stylus" scoped>
.formDiv {
  .lable {
    margin-right: 10px;
  }
}

.upload {
  float: right;
}

.recovery {
  height: 100%;
}

.paper-content {
  width: 85%;

  .card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-top: 20px;

    li {
      position: relative;
      padding: 15px 0;
      margin-bottom: 15px;
    }

    .questionIndex {
      float: left;
      font-size: 14px;
      color: #606266;
      padding: 0 12px 0 0;
      width: 60px;
      font-weight: bold;
    }

    .questionContent {
      margin-left: 60px;
      font-size: 14px;
      color: #303133;
      width: 85%;
    }

    .delectBtn {
      color: #1890ff;
      position: absolute;
      top: 15px;
      right: 0;
      cursor: pointer;
    }
  }
}

.ant-card-body {
  height: 100%;
}
</style>